package com.icexxx.ice_browser;

import java.awt.Color;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;

public class DataManager {

    public static void save(String requestMethod, String url, String param, String content, String key, Color color) {
        String savePath = DataContext.get("savePath");
        String savePathFull = DataContext.get("savePathFull");
        if (StrUtil.isBlankIfStr(savePath)) {
            throw new RuntimeException("保存的文件路径不存在");
        }
        if (savePathFull == null) {
            savePathFull = savePath + "/json.txt";
            DataContext.put("savePathFull", savePathFull);
        }
        String id = SelectedItemContext.getId();
        Request request = DataCenter.findById(id);
        if (request == null) {
            request = wrap(requestMethod, url, param, content, key, color);
            DataCenter.add(request);
        } else {
            DataCenter.update(request);
        }
        List<Request> all = DataCenter.getAll();
        byte[] serialize = ObjectUtil.serialize(all);
        FileUtil.writeBytes(serialize, savePathFull);
    }

    private static Request wrap(String requestMethod, String url, String param, String content, String key,
            Color color) {

        Request request = new Request();

        long createTime = System.currentTimeMillis();
        String id = SelectedItemContext.getId();
        int index = SelectedItemContext.getIndex();
        int version = createVersion(index);
        request.setId(id);
        request.setUrl(url);
        request.setKey(key);
        request.setMethod(requestMethod);
        request.setParam(param);
        request.setContent(content);
        request.setColor(color);
        request.setIndex(index);
        request.setVersion(version);
        request.setCreateTime(createTime);
        request.setUpdateTime(0);
        request.setRemark(key);// TODO
        request.setChecked(true);
        return request;
    }

    private static int createVersion(int index) {
        VersionManager.increment();
        AtomicInteger num = VersionManager.getNum();
        return num.intValue();
    }

}
